package com.joysuch.wwyt.dynamicdata;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.joysuch.wwyt.dynamicdata.enums.ProcessorSelector;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * <p>
 * The factory to create processor
 * </p>
 *
 * @author jwk
 * @since 2021-11-30
 */

public class DynamicDataProcessor implements IDynamicProcessorFactory {

    private final DynamicProcessorSelector dynamicProcessorSelector;

    public DynamicDataProcessor() {
        this.dynamicProcessorSelector = new DynamicProcessorSelector();
    }

    @Override
    public void writeProcess(Object dataObj, String bizType, String selector, Object bizId) {
        JSONArray jsonArray = JSONUtil.parseArray(dataObj, false);
        final ProcessorSelector processorSelector = ProcessorSelector.find(selector);
        if (processorSelector == ProcessorSelector.INSERT) {
            for (Object json : jsonArray) {
                if (JSONUtil.isJsonObj(json.toString())) {
                    JSON jsonData = JSONUtil.parse(json);
                    jsonData.putByPath(DynamicDataConstants.BIZ_ID, bizId);
                }
            }
        }
        dynamicProcessorSelector.select(selector).doProcess(DynamicParam.builder().targetData(jsonArray).bizType(bizType).build());
    }

    @Override
    public void importProcess(MultipartFile file, String handler, String selector) {
        dynamicProcessorSelector.select(selector).doProcess(DynamicParam.builder().file(file).dataDumpHandler(handler).build());
    }

    @Override
    public Object readProcess(Object dataObj, String dataDumpHandler, String selector) {
        Object result;
        switch (ProcessorSelector.find(selector)) {
            case EXPORT:
                result = dynamicProcessorSelector.select(selector).doProcess(DynamicParam.builder().targetData(dataObj).dataDumpHandler(dataDumpHandler).build());
                break;
            case SELECT:
                if (dataObj instanceof Page) {
                    List<?> content = ((Page<?>) dataObj).getContent();
                    Object dataList = dynamicProcessorSelector.select(selector).doProcess(DynamicParam.builder().targetData(content).build());
                    result = new PageImpl<>((List<?>) dataList, ((Page<?>) dataObj).getPageable(), ((Page<?>) dataObj).getTotalElements());
                } else {
                    result = dynamicProcessorSelector.select(selector).doProcess(DynamicParam.builder().targetData(dataObj).build());
                }
                break;
            default:
                throw new RuntimeException("selector does not exist");
        }
        return result;
    }

}
